<template>
    <page>
        <m-header>{{replace ? '更换手机号' : '绑定手机' }}</m-header>
        <m-header3 title="请输入重新绑定的手机号" v-if="replace"></m-header3>
        <m-group :gutter="replace? 0: 10">
            <m-input label="手机号" placehodler="请输入手机号" v-model="form.mobile"></m-input>
            <m-input-code label="验证码" placehodler="请输入验证码" :updateCode="getCode" v-model="form.code"></m-input-code>
        </m-group>
        <m-button class="mx12 mt40" @click.native="onSubmit">{{replace ? '确定更换' : '立即绑定'}}</m-button>
    </page>
</template>
<script>
  import checker, { required, phone } from '@/utils/checker'

  export default {
    data () {
      const replace = this.$route.query.replace
      this.phoneRepeat = (v) => {
        if (v.trim() == this.$store.getters.userInfo.mobile) {
          return '手机号不能为已绑定的手机号'
        }
        return true
      }
      return {
        replace,
        form: {
          mobile: null,
          code: null
        }
      }
    },
    computed: {},
    methods: {
      PitsPullData () {},
      PitsPushData () {},
      async getCode (next) {
        const checkerPhone = [this.form.mobile, phone('请输入正确的手机号'), this.phoneRepeat]
        if (!checker(checkerPhone)) return
        next()
        let body = await this.$post('member/sendMobile', this.form)
      },
      async onSubmit () {
        const checkerPhone = [this.form.mobile, phone('请输入正确的手机号'), this.phoneRepeat]
        const checkerCode = [this.form.code, required('请输入验证码')]
        if (!checker(checkerPhone, checkerCode)) return
        try {
          let body = await this.$post_loading('member/bindMobile', this.form)
          m_toast('绑定手机成功')
          this.$store.dispatch('updateUserInfo')
          await sleep(1500)
          history.back()
        } catch (e) {
          if (e.name == 401) m_alert('验证码错误')
          throw e
        }
      }
    },
    components: {}
  }
</script>
<style type="text/scss" lang="scss" scoped>

</style>
